import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken() ? getToken() : '',
    name: getUserInfo() ? getUserInfo().name : '',
    userId: getUserInfo() ? getUserInfo().userGuide.userId : '',
    userInfo: getUserInfo()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    commit('SET_TOKEN', userInfo.token)
    // commit('SET_NAME', userInfo.loginName)
    // commit('SET_USER_ID', userInfo.userGuide.userId)
    // commit('SET_USER_INFO', userInfo)
    setToken(userInfo.accessToken)
    // setUserInfo(userInfo)
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    removeUserInfo() // must remove  token  first
    resetRouter()
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

